﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LogisticDatabase.Models;
using LogisticDatabase.Data;

namespace LogisticDatabase
{
    public class ProductDataAccess : IDataAccess<Product>
    {
        public List<Product> listAll()
        {
           
            List<Product> products = new List<Product>();
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                products = ctx.tblProduct.Select(t => new Product { Id = t.ProductID, Name = t.ProductName, Price=t.ProductPrice, Factory =
                    new Factory { Id = t.tblFactory.FactoryID, Name = t.tblFactory.FactoryName, City = new City { Id = t.tblFactory.tblCity.CityID, Name = t.tblFactory.tblCity.CityName, Country = t.tblFactory.tblCity.CityCountry } }
                
                }).ToList();

            }
            return products;

        }
    
     public void edit(Product product)
       {
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                var c = ctx.tblProduct.FirstOrDefault(t => t.ProductID == product.Id);
                if (c != null)
                {
                    c.ProductName = product.Name;
                    c.ProductPrice = product.Price;
                    c.FactoryNameFK= product.Factory.Id;

                    ctx.SaveChanges();
                }


              
            }
        }
        public void add(Product product)
        {
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                tblProduct tc = new tblProduct();

                tc.ProductName = product.Name;
                tc.ProductPrice = product.Price;
                tc.FactoryNameFK=product.Factory.Id;

                ctx.tblProduct.Add(tc);

                ctx.SaveChanges();
            }
        }
        public void delete(Product product)
        {
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                var c = ctx.tblProduct.FirstOrDefault(t => t.ProductID == product.Id);
                if (c != null)
                {
                    ctx.tblProduct.Remove(c);
                    ctx.SaveChanges();
                }
            }

        }

    }
}
